package yt.kpool.activity.salesman;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yt.kpool.R;
import yt.kpool.activity.salesman.salesmanfragment.AgentAllGuestFragment;
import yt.kpool.activity.salesman.salesmanfragment.AgentSelfFragment;
import yt.kpool.activity.setting.agent.myguest.GuestChildAountActivity;
import yt.kpool.activity.setting.agent.myguest.GuestDetailActivity;
import yt.kpool.activity.setting.agent.myguest.HierarchicalModeActivity;
import yt.kpool.bean.CurrencyList;
import yt.kpool.bean.GuestDetailBean;
import yt.kpool.bean.LineChartTestBean;
import yt.kpool.interfac.OnAgentDetailsListener;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.AgentLineChartManager;
import yt.kpool.util.NetWorkUtil;
import yt.kpool.util.TimeUtil;
import yt.kpool.util.ToastUtil;
import yt.kpool.util.Util;
import yt.kpool.util.imageUtil.GlideUtil;
import yt.kpool.view.dialog.ErrorDialog;
import yt.kpool.view.dialog.LoadingDialog;
import yt.kpool.view.pop.CurrencyPopupWindow;

/**
 * 我的代理详情
 */
public class AgentDetailsActivity extends AppCompatActivity implements OnAgentDetailsListener {
    @BindView(R.id.tv_currrncyname)
    TextView tv_currrncyname;
    @BindView(R.id.iv_curreney)
    ImageView iv_curreney;
    @BindView(R.id.ll_currency)
    LinearLayout ll_currency;
    @BindView(R.id.tv_username)
    TextView tv_username;

 @BindView(R.id.tv_log)
    TextView tv_log;



    @BindView(R.id.tv_totalAmount)
    TextView tv_totalAmount;//总收益
    @BindView(R.id.tv_remount)
    TextView tv_remount;//已支付
    @BindView(R.id.tv_Balance)
    TextView tv_Balance;//余额
    @BindView(R.id.tv_ProportionName)
    TextView tv_ProportionName;//分层模式名称
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;


    private List<CurrencyList.DataBean> currencyListData;
    private CurrencyPopupWindow currencyPopupWindow;//币种选择
    private LoadingDialog loadingDialog;
    private int currencyId;//币种id
    private String currencycode = "";//币种code

    private int HierarchicalMode;//分层模式id

    public static void start(Activity mactivity, String UserID, String UserName) {
        Intent intent = new Intent(mactivity, AgentDetailsActivity.class);
        intent.putExtra("UserID", UserID);
        intent.putExtra("UserName", UserName);
        mactivity.startActivity(intent);
    }

    public String getName() {
        return getIntent().getStringExtra("UserName");
    }

    public String getUserID() {
        return getIntent().getStringExtra("UserID");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_agent_details);
        ButterKnife.bind(this);
        initTab();
        inits();

    }

    private void inits() {
        tv_username.setText(getName());
        loadingDialog = new LoadingDialog(this, 0);
        if (NetWorkUtil.checkNet(AgentDetailsActivity.this)) {
            getCurrrencyData();
        } else {

            ToastUtil.showToast(AgentDetailsActivity.this, getResources().getString(R.string.internet_error));
        }
    }


    /**
     * 获取币种数据
     */
    private void getCurrrencyData() {
        currencyListData = new ArrayList<>();
        if (NetWorkUtil.check(this)) {
            loadingDialog.show();

            NetHelperNew.GetCurrencyList(new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->", "币种列表：" + data);
                    CurrencyList currencyList = MyGson.getInstance().fromJson(data, CurrencyList.class);
                    if (currencyList.getType() == 1) {

                        currencyListData.addAll(currencyList.getData());
                        initCurrencyPopupWindow();
                        if (currencyList.getData().size() > 0) {
                            currencycode = currencyList.getData().get(0).getCode();
                            currencyId = currencyList.getData().get(0).getId();
                            GlideUtil.loadImage(AgentDetailsActivity.this, NetHelperNew.URL + currencyListData.get(0).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                            tv_currrncyname.setText(currencyListData.get(0).getCode().toUpperCase());

                        }
                        getData();

                    } else {

                        new ErrorDialog(AgentDetailsActivity.this, currencyList.getContent()).show();
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    loadingDialog.dismiss();

                    ToastUtil.showToast(AgentDetailsActivity.this, msg);
                }
            });


        }

    }

    /**
     * 币种选择pop初始化
     */
    private void initCurrencyPopupWindow() {
        currencyPopupWindow = new CurrencyPopupWindow(currencyListData, this, new CurrencyPopupWindow.OnSeleCurrencyLayoutListener() {
            @Override
            public void selectHouseLayout(int i) {
                currencyId = currencyListData.get(i).getId();
                currencycode = currencyListData.get(i).getCode();
                GlideUtil.loadImage(AgentDetailsActivity.this, NetHelperNew.URL + currencyListData.get(i).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                tv_currrncyname.setText(currencyListData.get(i).getCode().toUpperCase());
                getData();


            }
        });
    }

    /**
     * 获取客户详情数据
     */
    private void getData() {
        if (NetWorkUtil.check(this)) {
            EventBus.getDefault().post("AgentDetail");
            loadingDialog.show();

            NetHelperNew.GuestDetails(currencyId + "", getUserID(), new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->", "代理本身 详情：" + data);
                    GuestDetailBean guestDetailBean = MyGson.getInstance().fromJson(data, GuestDetailBean.class);
                    if (guestDetailBean.getType() == 1) {
                        GuestDetailBean.DataBean data1 = guestDetailBean.getData();
                        HierarchicalMode = data1.getProportionID();
                        DecimalFormat df = new DecimalFormat("#####0.00000000");

                        tv_totalAmount.setText(df.format(data1.getBalance() + data1.getTotalSett()));//总收益

                        tv_remount.setText(df.format(data1.getTotalSett()));//已支付

                        tv_Balance.setText(df.format(data1.getBalance()) );//余额

                        tv_ProportionName.setText(data1.getProportionName());//分层模式名称

//                        tv_log.setText(""+data1.getLoginNumber());

                    } else {
                        ToastUtil.showToast(AgentDetailsActivity.this, guestDetailBean.getContent());

                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    loadingDialog.dismiss();

                    ToastUtil.showToast(AgentDetailsActivity.this, msg);
                }
            });


        }
    }

    /**
     * 点击事件的处理
     *
     * @param view
     */
    @OnClick({R.id.ll_currency, R.id.ll_finish, R.id.ll_hierarchical, R.id.ll_log, R.id.btn_submit})
    public void onClick(View view) {
        switch (view.getId()) {


            case R.id.ll_finish:

                finish();
                break;
            case R.id.ll_hierarchical:
                HierarchicalModeActivity.start(AgentDetailsActivity.this, HierarchicalMode,3);
                break;
                case R.id.ll_log:
                LoginLogsActivity.start(AgentDetailsActivity.this,getUserID());
                break;
            case R.id.ll_currency:
                //选择币种
                if (currencyPopupWindow != null)
                    currencyPopupWindow.showAsDropDown(ll_currency, 0, 0);
                break;
            case R.id.btn_submit:
                //子账户列表
                GuestChildAountActivity.start(AgentDetailsActivity.this,getUserID(),currencyId+"",currencycode);
                break;


        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 32) {
            getData();
        }
    }

    private void initTab() {
        //添加标签
        tabLayout.addTab(tabLayout.newTab().setText("代理本身"));
        tabLayout.addTab(tabLayout.newTab().setText("全部客户"));
        viewPager.setAdapter(new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount()));

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        //绑定tab点击事件
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


    }

    /**
     * 监听重写
     * @return
     */
    @Override
    public String getAgentUserId() {
        return getUserID();
    }

    @Override
    public int getAgentCurrencyId() {
        return currencyId;
    }


    public class PageAdapter extends FragmentPagerAdapter {

        private int num;
        private HashMap<Integer, Fragment> mFragmentHashMap = new HashMap<>();

        public PageAdapter(FragmentManager fm, int num) {
            super(fm);
            this.num = num;
        }

        @Override
        public Fragment getItem(int position) {

            return createFragment(position);
        }

        @Override
        public int getCount() {
            return num;
        }

        private Fragment createFragment(int pos) {
            Fragment fragment = mFragmentHashMap.get(pos);

            if (fragment == null) {
                switch (pos) {
                    case 0:
                        fragment = new AgentSelfFragment();

                        break;
                    case 1:
                        fragment = new AgentAllGuestFragment();

                        break;

                }
                mFragmentHashMap.put(pos, fragment);
            }
            return fragment;
        }
    }
}
